﻿using HT.Future.Entities;
using HT.Future.IService;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HT.Future.Service
{
    public class BusinessService : BaseService<Business>, IBusinessService
    {

        private ILogger<IBusinessService> _logger;
        public BusinessService(HtDbContext dbContext, ILogger<IBusinessService> logger) : base(dbContext)
        {
            _logger = logger;
        }


        public async Task<List<Business>> GetBusinessesAsync(int userId)
        {
            var data = await DbContext.Set<WxUserToBusiness>().Include(a => a.Business).Where(a => a.UserId == userId).ToListAsync();
            return data.Select(a => a.Business).ToList();
        }

        public async Task<Business> CreateBusinessAsync(int userId, Business business)
        {
            await AddAsync(business);
            var relative = new WxUserToBusiness { BusinessId = business.Id, UserId = userId };
            await AddAsync(relative);
            return business;
        }

        public async Task<bool> DeleteBusinessAsync(int userId, int businessId)
        {
            var data = await DbContext.Set<WxUserToBusiness>()
                .Where(a => a.UserId == userId && a.BusinessId == businessId)
                .ToListAsync();
            if (data.Count == 0) return true;
            DbContext.Set<WxUserToBusiness>().RemoveRange(data);
            await DbContext.SaveChangesAsync().ConfigureAwait(false);
            return true;
        }

    }
}
